<template>
  <div>
    <h1>AI 你画我猜</h1>
    <!-- 根据游戏状态显示提示 -->
    <div v-if="gameStore.gamePhase === 'idle'" class="status-message">请在画布上开始绘图吧！🎨</div>

    <DrawingCanvas ref="drawingCanvasRef" />
    <div>
      <button @click="submitDrawing" :disabled="gameStore.isLoading">{{ gameStore.isLoading ? '正在猜测中...' : '提交猜测' }}</button>
    </div>
    <!-- 显示猜测结果、加载状态和错误信息 -->
    <div v-if="gameStore.isLoading" class="status-message">正在努力猜测中... 🤔</div>
    <div v-if="gameStore.error" class="status-message error">发生错误: {{ gameStore.error }}</div>
    <div v-if="gameStore.gamePhase === 'result' && gameStore.aiGuess" class="status-message result">
      AI 猜测: <strong>{{ gameStore.aiGuess }}</strong> 🎉
      <button @click="startNewRound">再来一轮</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import DrawingCanvas from './DrawingCanvas.vue';
import { guessDrawing } from '../services/api';
import { useGameStore } from '../stores/game'; // 确保导入

interface DrawingCanvasInstance {
  getCanvasDataURL: () => string | undefined;
  // 如果需要调用 clearCanvas，也需要在这里定义
  // clearCanvas: () => void;
}

const drawingCanvasRef = ref<DrawingCanvasInstance | null>(null);
const gameStore = useGameStore(); // 确保初始化

const submitDrawing = async () => {
  if (!drawingCanvasRef.value) {
    console.error('Drawing canvas component not available');
    gameStore.setError('画布组件不可用');
    return;
  }
  const imageDataUrl = drawingCanvasRef.value.getCanvasDataURL();

  if (imageDataUrl) {
    gameStore.setDrawingData(imageDataUrl); // 在调用 API 前设置数据
    await guessDrawing(imageDataUrl);
  } else {
    console.error('Failed to get image data from canvas');
    gameStore.setError('无法从画布获取图像数据');
  }
};

const startNewRound = () => {
  gameStore.resetGame();
  // 清空画布 - 假设 DrawingCanvas 暴露了 clearCanvas 方法
  // 需要在 DrawingCanvas 的 defineExpose 中添加 clearCanvas
  // if (drawingCanvasRef.value) {
  //   drawingCanvasRef.value.clearCanvas();
  // }
};

</script>

<style scoped>
h1 {
  text-align: center;
}
div > div {
    text-align: center;
    margin-top: 15px;
}
.status-message {
  text-align: center;
  margin-top: 20px;
  font-size: 1.2em;
}
.error {
  color: red;
}
.result strong {
  color: green;
}
.result button {
    margin-left: 15px;
    font-size: 0.8em;
}
</style>
